package com.wframe.project.jnd.util;

import com.wframe.project.jnd.entity.MoneyOffItem;
import org.springframework.util.Assert;

import java.math.BigDecimal;
import java.util.List;

/**
 * Created by lwb on 2017/6/7.
 */
public class MoneyOffPromotionHandlerChain {
    private List<MoneyOffItem> items;
    private MoneyOffPromotionHandler handler;

    public MoneyOffPromotionHandlerChain(List<MoneyOffItem> items) {
        Assert.notEmpty(items, "满减促销必须有优惠");
        this.items = items;
        setHandler();
    }

    public void setHandler() {
        int size = this.items.size();
        int i = 0;
        this.handler = new MoneyOffPromotionHandler(this.items.get(0));
        if (size > 1) {
            addHandler(this.handler, this.items.get(++i), i);
        }
    }

    private void addHandler(MoneyOffPromotionHandler handler, MoneyOffItem item, int i) {
        MoneyOffPromotionHandler next = new MoneyOffPromotionHandler(item);
        handler.setSuccessor(next);

        if (i == this.items.size() - 1) {
            return;
        }
        addHandler(next, this.items.get(++i), i);
    }

    public MoneyOffItem handle(BigDecimal totalPrice) {
        return this.handler.handleRequest(totalPrice);
    }

}
